﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QDFeedParser;
using Proggy.Web.Cms.Core.PropertyTypes;


namespace Proggy.Web.Cms.Core.AutoRenderModels
{
    /// <summary>
    /// Render model for Rss feed
    /// </summary>
    public class RssReaderAutoRenderModel
    {
        public RssReaderAutoRenderModel(RssReader configData) {
            try
            {
                // set url etc
                this.FeedUrl = configData.FeedUrl;
                this.FeedUri = new Uri(this.FeedUrl);


                // get feed fac
                var fac = new HttpFeedFactory();

                // get feed
                this.Feed = fac.CreateFeed(this.FeedUri);

                // get items
                this.Items = this.Feed.Items.Take(configData.Count).ToList();

                // check name
                if (string.IsNullOrEmpty(configData.Name))
                {
                    // get name from feed
                    var name = this.Feed.Title;

                    // check
                    if (!string.IsNullOrEmpty(name))
                    {
                        this.Name = name;
                    }
                }
                else {
                    this.Name = configData.Name;
                }

                // check more
                if (string.IsNullOrEmpty(configData.MoreUrl))
                {
                    // get name from feed
                    var name = this.Feed.Link;

                    // check
                    if (!string.IsNullOrEmpty(name))
                    {
                        this.MoreUrl = name;
                    }
                }
                else {
                    this.MoreUrl = configData.MoreUrl;
                }
            }
            catch { 
                // TODO: set fake items etc
            }
        }
        public string Name { get; set; }
        public List<BaseFeedItem> Items { get; set; }
        public string FeedUrl { get; set; }
        public Uri FeedUri { get; set; }
        public string MoreUrl { get; set; }
        public IFeed Feed { get; set; }
    }
}
